package com.nlp.visualization.crawler.pipeline;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hankcs.hanlp.corpus.io.IOUtil;
import com.nlp.visualization.common.CONSTANTS;
import com.nlp.visualization.pojo.crawler.NewsJson;
import com.nlp.visualization.utils.PropertyUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.IOUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author LXM
 * @Title:
 * @Description: 用户存储爬取的新闻的缓冲区，当数量达到N条时，保存为json文件。
 * @date 2018/3/4上午11:55
 */
public class JsonBuffer {

    private Logger logger = LoggerFactory.getLogger(JsonBuffer.class);

    private static final int N = 20;

    private volatile static JsonBuffer instance;

    private volatile List jsonList;

    private volatile Integer count = 0;

    private Gson gson = new GsonBuilder().setPrettyPrinting().create();


    private JsonBuffer() {
        jsonList = new LinkedList();
    }

    public static JsonBuffer getInstance() {
        if (instance == null) {
            synchronized (JsonBuffer.class) {
                if (instance == null) {
                    instance = new JsonBuffer();
                }
            }
        }
        return instance;
    }


    public void addObjectToList(Object object) {

        synchronized (jsonList) {
            jsonList.add(object);
        }
    }

    /**
     * 以json格式保存今天的新闻。
     *
     * @param source
     * @param list
     * @return
     */
    public boolean saveTodayNews(String source, String date) {


        NewsJson news = new NewsJson();
        news.setItems(jsonList);
        news.setDate(date);
        news.setSource(source);
        String jsonTemp = gson.toJson(news);
        String fileName = getFileName(date);
        logger.info("正在保存文件：" + fileName);
        try {
            if (IOUtil.isFileExisted(fileName)) {
                IOUtil.deleteFile(fileName);
            }
            File file = new File(fileName);

            FileUtils.writeStringToFile(file, jsonTemp, "UTF-8");
            //任务完成，清空list
            jsonList.clear();
            return true;
        } catch (Exception e) {
            logger.error("文件不存在");
            e.printStackTrace();
            return false;
        }
    }


    private String getFileName(String date) {

        return PropertyUtil.getInstance("config").getProperty("lda.base") + PropertyUtil.getInstance("config").getProperty("lda.news.origin") + "/" + date + ".json";

    }
}
